#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
   public:
    string reverseWords(string s) {
        s = "  " + s + "  ";
        vector<string> temp;
        string addStr = "";
        for (int i = 0; i < s.size() - 1; i++) {
            char left = s[i];
            char right = s[i + 1];
            if (left == ' ') {
                if (right != ' ')
                    addStr.push_back(right);
            } else {
                if (right == ' ') {
                    temp.push_back(addStr);
                    addStr = "";
                } else
                    addStr.push_back(right);
            }
        }
        reverse(temp.begin(), temp.end());
        string res = "";
        for (int i = 0; i < temp.size(); i++) {
            if (i != temp.size() - 1) {
                res += temp[i] + ' ';
            } else {
                res += temp[i];
            }
        }
        return res;
    }
};
int main() {
    Solution s;
    cout << "(" << s.reverseWords(" this is    a  good   example  ") << ")" << endl;
    cout << "(" << s.reverseWords(" this is    a  good   exampl e") << ")" << endl;
    return 0;
}
